package middleware

import (
	"github.com/didip/tollbooth"
	"github.com/didip/tollbooth/limiter"
	"github.com/labstack/echo/v4"
	"sofuny/utils"
)

// userAgent
func UserAgentMiddleware(next echo.HandlerFunc) echo.HandlerFunc {
	return func(ctx echo.Context) error {
		// 判断有没有 UserAgent
		if ctx.Request().UserAgent() == "" {
			return ctx.JSON(403, utils.Response{
				Code: 403,
				Msg: "没有访问权限",
				Data: nil,
				Total: 0,
				Time: utils.FormatTime(),
			})
		}
		return next(ctx)
	}
}

// http 请求限制
func LimitMiddleware(lmt *limiter.Limiter) echo.MiddlewareFunc {
	return func(next echo.HandlerFunc) echo.HandlerFunc {
		return echo.HandlerFunc(func(ctx echo.Context) error {
			status := tollbooth.LimitByRequest(lmt, ctx.Response(), ctx.Request())
			if status != nil {
				return ctx.JSON(status.StatusCode, utils.Response{
					Code: status.StatusCode,
					Msg: status.Message,
					Data: nil,
					Total: 0,
					Time: utils.FormatTime(),
				})
			}
			return next(ctx)
		})
	}
}

func LimitHandler(lmt *limiter.Limiter) echo.MiddlewareFunc {
	return LimitMiddleware(lmt)
}

// http referer
func RefererMiddleware(next echo.HandlerFunc) echo.HandlerFunc {
	return func(ctx echo.Context) error {
		// 判断有没有 UserAgent
		if ctx.Request().Referer() != "https://sofuny.cn" {
			return ctx.JSON(403, utils.Response{
				Code: 403,
				Msg: "没有访问权限",
				Data: nil,
				Total: 0,
				Time: utils.FormatTime(),
			})
		}
		return next(ctx)
	}
}


// ServerHeader middleware adds a `Server` header to the response.
func AdminServerMiddleware(next echo.HandlerFunc) echo.HandlerFunc {
	return func(ctx echo.Context) error {
		// 判断token
		if ctx.Request().Header.Get("token") == "" {
			return ctx.JSON(403, utils.Response{
				Code: 403,
				Msg: "没有访问权限",
				Data: nil,
				Total: 0,
				Time: utils.FormatTime(),
			})
		}
		// 通过验证 返回
		return next(ctx)
	}
}
